//////////////////////////////////////////////////////////////////////////////
//
//  Created by Philip Mulcahy on 08/05/2012.
//  Copyright (c) 2012 Philip Mulcahy. All rights reserved.
//
//  This file is part of the note-recog library.
//
//  note-recog is free software: you can redistribute it and/or modify
//  it under the terms of version 3 of the GNU Lesser General Public License 
//  as published by the Free Software Foundation.
//
//  note-recog is distributed is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with note-recog.  If not, see <http://www.gnu.org/licenses/>.
//
//////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include "Spectrum.h"
#include <cmath>

std::map<float, const FastFourierTransform::Functor *> Spectrum::_fftCache;

Spectrum Spectrum::fromTimeDomain(const std::vector<short>& timeDomain, float samplingFreq)
{
    const FastFourierTransform::Functor * func = 0;
    auto fft_itr = _fftCache.find(samplingFreq);
    if(fft_itr == _fftCache.end())
    {
        func = new FastFourierTransform::Functor(samplingFreq);
        _fftCache[samplingFreq] = func;
        fft_itr->second = func;
    }
    else
    {
        func = fft_itr->second;
    }
    
    return (*func)(timeDomain);
}

float Spectrum::rms() const
{
    float sigmax2 = 0.;
    const size_t n = _abs->size();
    for( float x : *_abs )
    {
        sigmax2 += ( x * x );
    }
    const float meansquare = sigmax2 / n;
    const float rms = std::sqrt( meansquare );
    return rms;
}

float Spectrum::quality() const
{
    float sigmaabsdiff = 0.;
    const size_t n = _abs->size() - 1;
    for( std::vector<float>::const_iterator it = _abs->begin();
        it != _abs->end() - 1;
        ++it )
    {
        const float& x = *it;
        const float& nextx = *( it + 1 );
        const float diff = nextx - x;
        const float absdiff = std::abs( diff );
        sigmaabsdiff += absdiff;
    }
    const float meanabsdiff = sigmaabsdiff / n;
    const float rmsval = rms();
    const float quality = rmsval / meanabsdiff;
    
    return quality;
}